package com.situ.mall.controller.back;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.situ.mall.util.ImageServerUtil;
import com.situ.mall.util.JSONResult;
import com.situ.mall.util.QiniuUtil;

@Controller
@RequestMapping("/upload")
public class UploadController {

	@ResponseBody
	@RequestMapping("/uploadImg")
	public JSONResult uploadImg(MultipartFile file) throws IOException {
		// 文件的名字要返回到前台表单，在insert时候插入数据库
		String newFileName = "";
		if (ImageServerUtil.IMG_SERVER == ImageServerUtil.QINIU) {
			newFileName = QiniuUtil.uploadImage(file.getBytes());
		} else {
			newFileName = uploadToLocal(file);
		}
		
		return JSONResult.ok("", newFileName);
	}

	private String uploadToLocal(MultipartFile file) {
		// 为了防止文件重名(重名的文件会被覆盖丢失)，所以要生成一个不重复的随机的名字
		String name = UUID.randomUUID().toString().replace("-", "");
		// ec428487a2cb415ebb97ee51437b774d
		String fileName = file.getOriginalFilename();// aa.jpg
		String extension = FilenameUtils.getExtension(fileName);// jpg
		String newFileName = name + "." + extension;// ec428487a2cb415ebb97ee51437b774d.jpg
		//  d:/pic/ec428487a2cb415ebb97ee51437b774d.jpg
		String filePath = "D:\\pic\\" + newFileName;
		try {
			file.transferTo(new File(filePath));
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return newFileName;
	}
	
	public static void main(String[] args) {
		String uuid = UUID.randomUUID().toString();
		// 79a254a1-703f-4aa2-ba67-5749ccf5744b
		System.out.println(uuid);
		// ec428487a2cb415ebb97ee51437b774d
		System.out.println(uuid.replace("-", ""));
	}
}
